package com.example.artgallery.repository

import com.example.artgallery.model.Artwork
import java.io.File
import java.util.Date

class ArtRepository(private val rootDir: File) {
    private val artworksDir = File(rootDir, "artworks").apply { mkdirs() }
    
    fun getAllArtworks(): List<Artwork> {
        return artworksDir.listFiles()?.flatMap { folder ->
            folder.listFiles()?.mapNotNull { file ->
                Artwork(
                    id = file.hashCode().toLong(),
                    title = file.nameWithoutExtension,
                    folder = folder.name,
                    imagePath = file.absolutePath,
                    createDate = Date(file.lastModified()).toString()
                )
            } ?: emptyList()
        } ?: emptyList()
    }
    
    fun getArtworksByFolder(folder: String): List<Artwork> {
        val targetFolder = File(artworksDir, folder)
        return targetFolder.listFiles()?.mapNotNull { file ->
            Artwork(
                id = file.hashCode().toLong(),
                title = file.nameWithoutExtension,
                folder = folder,
                imagePath = file.absolutePath,
                createDate = Date(file.lastModified()).toString()
            )
        } ?: emptyList()
    }
    
    fun addArtwork(artwork: Artwork) {
        val folder = File(artworksDir, artwork.folder).apply { mkdirs() }
        val destFile = File(folder, "${artwork.title}.jpg")
        File(artwork.imagePath).copyTo(destFile, overwrite = true)
    }
    
    fun deleteFolder(folderName: String): Boolean {
        val folder = File(artworksDir, folderName)
        return if (folder.exists()) {
            folder.deleteRecursively()
            true
        } else {
            false
        }
    }
}